# coding:utf-8
# @Time    : 2018/9/23 17:59
# @Author  : 0x007er
# @File    : tcurl.py
# @Software: PyCharm
import pycurl
import requests
from io import BytesIO
from retrying import retry
class OKHTTP():
    def retry_if_result_none(result):
        return result is False
    @retry(stop_max_attempt_number=3, wait_fixed=500, retry_on_result=retry_if_result_none)
    def DOPCURL(self,url,headers,AllowRedirects,timeout,charset):
        try:
            header = []
            for key in headers.keys():
                head = key+': '+headers[key]
                header.append(head)
            if AllowRedirects == True:
                AllowRedirects = 1
            else:
                AllowRedirects = 0
            bytes = BytesIO()
            c = pycurl.Curl()
            c.setopt(pycurl.URL, url)
            c.setopt(pycurl.CONNECTTIMEOUT, timeout) #连接超时
            c.setopt(pycurl.WRITEFUNCTION, bytes.write) #写进字节串
            c.setopt(pycurl.TIMEOUT, timeout) #读取超时
            c.setopt(pycurl.FOLLOWLOCATION, AllowRedirects)  # 重定向
            c.setopt(pycurl.MAXREDIRS, 2)  # 最大重定向次数
            c.setopt(pycurl.SSL_VERIFYPEER, 0)  # SSL验证1
            c.setopt(pycurl.SSL_VERIFYHOST, 0)  # SSL验证2
            c.setopt(pycurl.HEADER, True)  #扩展headrs
            c.setopt(pycurl.HTTPHEADER, header)
            c.setopt(pycurl.USERAGENT,"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.168 Safari/537.36")
            c.perform()
            content = bytes.getvalue()
            #智能解码耗时太长,改为人工选择编码
            result = content.decode(charset, 'ignore')
            del header
            del content
            return result
        except Exception  as e:
            print('PCurl:',e)
            return False
    @retry(stop_max_attempt_number=3, wait_fixed=500, retry_on_result=retry_if_result_none)
    def req(self,url,headers,AllowRedirects,timeout,charset):
        try:
            return str(requests.head(url, headers=headers, timeout=(timeout, timeout), allow_redirects=AllowRedirects,verify=False).headers)
        except Exception as e:
            print('req',e)
            return False
    def GET(self,url,headers,AllowRedirects,timeout,charset):
        try:
            return self.DOPCURL(url,headers,AllowRedirects,timeout,charset)
        except Exception as e:
            print('PCURL',e)
            return False
    def HEAD(self,url,headers,AllowRedirects,timeout,charset):
        try:
            return self.req(url,headers,AllowRedirects,timeout,charset)
        except Exception as e:
            print('PCURL',e)
            return False